import threading
import math
import struct
import numpy as np

class AudioThread(threading.Thread):
    def __init__(self, stream, project):
        threading.Thread.__init__(self)
        self.stream = stream
        self.project = project
        self.sampleIndex = 0
        self.stopped = False

    def exit(self):
        self.stopped = True

    def run(self):
        while self.stream.is_active() and not self.stopped:
            avail = self.stream.get_write_available()
            if avail != 0:
                avail = int(avail / 2) * 2
                sample = self.project.GetInterleavedSample()
                offsetSample = np.roll(sample, -self.sampleIndex)
                outputBuffer = offsetSample[:avail].astype(np.float32).tostring()
                self.stream.write(outputBuffer)
                self.sampleIndex = (self.sampleIndex + avail) % len(sample)
                self.project.samplePosition = self.sampleIndex / len(self.project.sample)

